import JSLogger from './JsLogger';
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
import JsDataStore from './JsDataStore';
import screenshot from '@ohos.screenshot'
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { fileUri } from '@kit.CoreFileKit';

interface ScreenShotPixMap {
  w: number;
  h: number;
  buffer?: ArrayBuffer;
}

export class JsServices {
  constructor() {
  }

  async screenShot() : Promise<ScreenShotPixMap> {
    let result: ScreenShotPixMap = { w: 0, h: 0 }

    try {
      let pickInfo:screenshot.PickInfo = await screenshot.pick();
      let length: number = pickInfo.pixelMap.getPixelBytesNumber();
      let info: image.ImageInfo = pickInfo.pixelMap.getImageInfoSync();
      let buffer: ArrayBuffer = new ArrayBuffer(length);

      console.warn('pick Pixel bytes number: ' + length);
      console.warn('pick Rect: ' + JSON.stringify(pickInfo.pickRect));

      pickInfo.pixelMap.readPixelsToBufferSync(buffer);
      pickInfo.pixelMap.release();
      result.buffer = buffer;
      result.w = info.size.width;
      result.h = info.size.height;
    } catch (exception) {
      console.error('Failed to pick Code: ' + JSON.stringify(exception));
    };

    return result;
  }

  async openUrl(inUri: string): Promise<boolean> {
    let wantInfo: Want = this.structureWant(inUri);
    let context: common.UIAbilityContext = JsDataStore.getValidContext();
    await context.startAbility(wantInfo).then(() => {
      JSLogger.info("open url：%{public}s success", inUri)
    }).catch((_err: BusinessError) => {
      JSLogger.error("open url：%{public}s error", inUri)
      return false;
    })
    return true;
  }

  async openDocument(inUri: string): Promise<boolean> {
    let wantInfo: Want = this.structureWant(inUri);
    let context: common.UIAbilityContext = JsDataStore.getValidContext();
    await context.startAbility(wantInfo).then(() => {
      JSLogger.info("open Document：%{public}s success", inUri)
    }).catch((_err: BusinessError) => {
      JSLogger.error("open Document：%{public}s error", inUri)
      return false;
    })
    return true;
  }

  structureWant(inUri: string) : Want{
    let isDir :boolean = false;
    let isDetermineSuccess:boolean = false;
    let wantInfo : Want;
    let path:string;
    let uri:string;
    try {
      path = new fileUri.FileUri(inUri).path;
      uri = fileUri.getUriFromPath(path);
      let stat = fs.statSync(path);
      isDir = stat.isDirectory();
      isDetermineSuccess = true;
    } catch (exception) {
      console.error('Failed to pick Code: ' + JSON.stringify(exception));
    }
    JSLogger.info("open url structureWant inUri ：%{public}s, path ：%{public}s, uri ：%{public}s", inUri, path, uri)
    //目录使用文管打开
    if(isDetermineSuccess && isDir) {
      wantInfo = {
        abilityName: "MainAbility",
        bundleName: "com.huawei.hmos.filemanager",
        parameters: {fileUri:uri}
      }
    } else{
      wantInfo = {
        action: 'ohos.want.action.viewData',
        entities: ['entity.system.browsable'],
        uri: inUri
      }
    }

    return wantInfo;
  }
}